<?php

class Manngercustomer extends Admin_Controller
{
    function __construct()
    {

        parent::__construct();
        error_reporting(E_ALL ^ E_NOTICE);
        $this->load->helper('url_helper');
        $this->load->helper('url');
//        $this->load->model('goods_model');
        $this->load->model('users_model');
        $this->load->model('customer_model');
//        header("Access-Control-Allosw-Origin: http://runapi.showdoc.cc");
//        header("Access-Control-Allow-Credentials : true");
    }

    // 经理发送客户密码
    function send_pwd(){
        $post = $_POST;
        $max_sms_count = $post['max_sms_count']?$post['max_sms_count']:3;
        if ($post['customer_id'] && $post['manager_id'])
        {
            $query = $this->db->get_where('customer',array('id'=>$post['customer_id'],'manager_id'=>$post['manager_id']));
            $res = $query->row_array();
            if(!$res)
            {
                $data['status'] = "fail";
                $data['msg'] = "没有绑定该用户";
                $data['data'] = "";
                json_send($data);
                exit();
            }
            $query_manager = $this->db->get_where('manager',array('id'=>$post['manager_id']));
            $res_manager = $query_manager->row_array();
            if(!$res_manager)
            {
                $data['status'] = "fail";
                $data['msg'] = "经理不存在";
                $data['data'] = "";
                json_send($data);
                exit();
            }
            $info = $res;
            $info_manager = $res_manager;
            // 新增查询客户的登录账户
            $url = $this->config->item("shop_base_url")."citymanagerapi/customer_detail/";
            $data1['key'] = md5_key();
            $data1['id'] = $post['customer_id'];
            $get_data = curl_request($url,$data1);
            $get_data = json_decode($get_data);
            if ($get_data->code==200){
                $account_shop = $get_data->data->account;
            }
            $account = $account_shop ? $account_shop : $info_manager['name'];
            $msg = "【文具1号】尊敬的客户，销售经理".$info_manager['name']."为您创建专属采购帐号：".$account."，密码：".$info['password']."。办公用品阳光采购，就上www.wjyh.com";
            $data['status'] = "success";
            $data['msg'] = "尊敬的客户";
            $data['data'] = "";
            // 增加短信计数功能
            $sms_res = $this->customer_model->sms_send_count($post['manager_id'],$post['customer_id']);
            if(!$sms_res)
            {
                $data['status'] = "fail";
                $data['msg'] = "数据错误";
                $data['data'] = "";
                json_send($data);
                exit();
            }
            $sms_count = $sms_res['count'];
            $sms_id = $sms_res['id'];

            // 重写发短信
            $this->load->library('message', '', 'mylib');
            $message_lib = $this->mylib;
            // end

            if($sms_count < $max_sms_count) {
                $bool_dx = $message_lib->send_msg($info['customer_tel'],$msg);
                if ($bool_dx['status'] == 'success'){
                    $data['msg'].="，短信发送成功";
                    // 发送短信新增一条
                    $this->customer_model->sms_send_add($sms_id);
                    $query = $this->db->get_where('send_password_count',array('id'=>$sms_id));
                    $res = $query->row_array();
                    $data['data']['count'] = $res['count'];

                }else{
                    $data['msg'] .= "，".$bool_dx['msg'];
                }
            }else{
                $data['msg'].="，提示短信每天最多只能发送".$max_sms_count."条，请明天再试";
            }

        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 修改客户基本资料
    function update_customer(){
        $post = $_POST;
        $upd_data = json_decode($post['data'],true);
        if ($post['customer_id'] && $post['manager_id'] && $upd_data){
            //验证下格式
            $rs = $this->customer_model->validate($upd_data);
            if($rs['status']=='fail'){
                json_send($rs);exit;
            }
            //判断是否包含规定的几个键
            $exit = 0;
            $fileds = array("customer_name","customer_tel","customer_email","company","position");
            foreach ($fileds as $v) {
                if (array_key_exists($v, $upd_data)) {
                    $exit = 1;
                }else{
                    $exit = 0;
                    break;
                }
            }
            // 判断是否存在绑定关系
            $manager = $this->db->where(["id"=>$post['customer_id']])->get("customer")->result_array();
            if(!$manager)
            {
                $data['status'] = "fail";
                $data['msg'] = "没有此客户";
                $data['data'] = "";
                json_send($data);
                exit();
            }
            if($manager[0]['manager_id'] != $post['manager_id'])
            {
                $data['status'] = "fail";
                $data['msg'] = "当前用户没有权限";
                $data['data'] = "";
                json_send($data);
                exit();
            }
            if($exit){
                $res = $this->customer_model->update_customer($post['customer_id'],$upd_data);
                if($res)
                {
                    $data['status'] = "success";
                    $data['msg'] = "更新成功";
                    $data['data'] = "";

                    // 推送企业站修改
                    $data['name'] = $upd_data['customer_name'];
                    $data['tel'] = $upd_data['customer_tel'];
                    $data['email'] = $upd_data['customer_email'];
                    $data['company'] = $upd_data['company'];
                    // 同步到企业站
                    $shop_user_id = $this->db->where(array("id"=>$post['customer_id']))->get("customer")->row_array()['shop_customer_id'];
                    $url = $this->config->item("business_station_base_url")."customer_api/update_user_base_info_api/";
                    $data['shop_user_id'] = $shop_user_id;
                    //发送数据
                    $res_data = curl_request($url,$data);

                }else{
                    $data['status'] = "fail";
                    $data['msg'] = "更新失败";
                    $data['data'] = "";
                }
            }else{
                $data['status'] = "fail";
                $data['msg'] = "参数错误";
                $data['data'] = "";
            }
        }else{
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
        }
        json_send($data);
    }

    // 获取客户订单列表(订单总数列表使用) cj
    function customer_order_detail_list(){
        $requst = $_GET;
        if(!$requst['manager_id'] || !$requst['customer_id'])
        {
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        $res = $this->customer_model->customer_order_detail_list($requst);
        if(!$res)
        {
            $data['status'] = "success";
            $data['msg'] = "没有数据";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        $data['msg'] = "获取成功";
        $data['status'] = "success";
        // 测试cj
//        foreach($res['order_list'] as $key => $or)
//        {
//            /**
//             *
//            "product_id": "15829",
//            "product_name": "百乐（PILOT）学生笑脸钢笔 FKA-1SR",
//            "product_price": "100.19",
//            "product_num": "1",
//            "default_image": "http://www.wjyh.com/imgserver2/goods/m08/htmnYh10982194977.jpg",
//            "product_spec": [
//            "颜色 : F 笔尖 细字",
//            "包装 : 支"
//            ],
//            "refund": ""
//             */
//            $res['order_list'][$key]['product_info']['product_id'] = '15829';
//            $res['order_list'][$key]['product_info']['product_name'] = '百乐（PILOT）学生笑脸钢笔 FKA-1SR';
//            $res['order_list'][$key]['product_info']['product_price'] = '100.19';
//            $res['order_list'][$key]['product_info']['product_num'] = '1';
//            $res['order_list'][$key]['product_info']['default_image'] = "http://www.wjyh.com/imgserver2/goods/m08/htmnYh10982194977.jpg";
//            $res['order_list'][$key]['product_info']['product_spec'] = array('颜色 : F 笔尖 细字','包装 : 支');
//            $res['order_list'][$key]['product_info']['refund'] = '';
//
//        }
        $data['data'] = $res;
        json_send($data);
    }
    // 获取客户总订单列表（客户详情使用） cj
    function customer_order_list(){
        $requst = $_GET;
        if(!$requst['manager_id'] || !$requst['customer_id'])
        {
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        $res = $this->customer_model->customer_order_list($requst);
        if(!$res)
        {
            $data['status'] = "success";
            $data['msg'] = "没有数据";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        $data['msg'] = "获取成功";
        $data['status'] = "success";
        $data['data'] = $res;
        json_send($data);
    }

    // 获取客户管理列表
    function mcustomer_list(){
        /**
         * 搜索关键字
         * manager_id 经理ID
         * customer_tel 用户手机号
         * customer_name 客户姓名
         * company 客户公司
         * keyword 搜索关键词
         * order_status 订单状态 1:全部状态，2:未下单,3：已下单
         * order_month 订单时间范围 3，6，12
         * order_sort 订单排序方式 1:综合排序，2:创建时间，3:登录时间，4:订单数量
         * page 	分页页码
         * psize    每页显示条数，默认10，最大100
         * asc_type 排序方式 默认降序 desc 1:降序，2:升序
         */
        $requst = $_GET;
        if(!$requst['manager_id'])
        {
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        if($requst['keyword'])
        {
            if(preg_match("/^1[34578]\d{9}$/", $requst['keyword'])){
                $requst['customer_tel'] = $requst['keyword'];
            }else{
                $requst['customer_name'] = $requst['keyword'];
                $requst['company'] = $requst['keyword'];
            }
        }
        $res = $this->users_model->get_user_orders($requst);
        if(!$res)
        {
            $data['status'] = "success";
            $data['msg'] = "没有数据";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        $data['msg'] = "获取成功";
        $data['status'] = "success";
        $data['data'] = $res;
        json_send($data);
    }

    // 获取客户账户详情
    function get_customer_info(){

        /**
         * customer_id 客户ID
         */
        $requst = $_GET;
        if(!$requst['customer_id'])
        {
            $data['status'] = "fail";
            $data['msg'] = "参数错误";
            $data['data'] = "";
            json_send($data);
            exit();
        }
        $res = $this->customer_model->get_customer_info($requst);
        if(!$res)
        {
            $data['status'] = "success";
            $data['msg'] = "没有数据";
            $data['data'] = "";
        }else{
            $data['status'] = "success";
            $data['msg'] = "获取成功";
            $data['data'] = $res;
        }
        json_send($data);
        exit();

    }

}